package com.szewec.ps.ui.road.facilities.investigation.task.roadside.facilities;

import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;

import com.alibaba.fastjson.JSONObject;
import com.szewec.ps.R;
import com.szewec.ps.base.BaseMediaPickerActivity;
import com.szewec.ps.base.Constants;
import com.szewec.ps.base.FileUpload;
import com.szewec.ps.databinding.ActivityRoadsideFacilitiesBinding;
import com.szewec.ps.model.PresentValue;
import com.szewec.ps.model.road.facilities.investigation.task.RoadFacilitiesInvestigationTaskDTO;
import com.szewec.ps.myview.indicator.IndicatorViewPager;
import com.szewec.ps.myview.indicator.OnTransitionTextListener;
import com.szewec.ps.myview.indicator.slidebar.DrawableBar;
import com.szewec.ps.util.imagepicker.adapter.CustomPickerAdapterShowAndEdit;
import com.szewec.ps.util.imagepicker.data.MediaFile;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;

public class RoadsideFacilitiesActivity extends BaseMediaPickerActivity {
    private ActivityRoadsideFacilitiesBinding binding;

    // 路段设施调查任务DTO
    private RoadFacilitiesInvestigationTaskDTO.RoadFacilitiesTaskDTO roadFacilitiesTaskDTO;
    // 用于区分新增还是修改还是详情展示
    private String modeFlag; // 用于区分新增还是修改还是详情展示

    // 标签页
    private String[] versions = {"公交站点", "地铁站点", "地铁出入口", "路内停车", "自行车停放点", "过街道设施", "收费站", "交通标志", "照片"};
    // 标签页相关
    private Point screenPoint;
    private List<Integer> textWidths = new ArrayList<>();
    DrawableBar drawableBar;
    private IndicatorViewPager indicatorViewPager;
    private MyAdapter myAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_roadside_facilities);
        ButterKnife.bind(this);

        initData();
        initTitleBar();
        initRecycleView();
        indicatorViewPager.notifyDataSetChanged();
    }

    private void initData() {
        // 获取intent中的数据
        PresentValue<RoadFacilitiesInvestigationTaskDTO.RoadFacilitiesTaskDTO> presentValue =
                (PresentValue<RoadFacilitiesInvestigationTaskDTO.RoadFacilitiesTaskDTO>) getIntent().getSerializableExtra(Constants.EXTRA_KEY.ROAD_INVESTIGATION_TASK_DTO);
        //获取是新增还是修改还是详情展示
        assert presentValue != null;
        modeFlag = presentValue.getFlag();
        roadFacilitiesTaskDTO = presentValue.getT();
        Log.i("道路沿线设施getData", JSONObject.toJSONString(roadFacilitiesTaskDTO));
    }

    private void initTitleBar() {
        //显示返回按钮
        binding.titleBar.setLeftLayoutVisibility(View.VISIBLE);
        binding.titleBar.setLeftLayoutClickListener(this::finish);
        //设置右边按钮
        binding.titleBar.setRightTextVisibility(View.VISIBLE);
        binding.titleBar.setRightText("保存");
        binding.titleBar.setRightLayoutClickListener(() -> {
            myAdapter.getFragmentsData();
            Intent intent = new Intent();
            PresentValue<RoadFacilitiesInvestigationTaskDTO.RoadFacilitiesTaskDTO> presentValue = new PresentValue<>(modeFlag, roadFacilitiesTaskDTO);
            intent.putExtra(Constants.EXTRA_KEY.ROAD_INVESTIGATION_TASK_DTO, presentValue);
            setResult(Constants.RESULT_CODE.NEED_REFRESH, intent);
            finish();
        });
    }

    private void initRecycleView() {
        float unSelectSize = 15; //未被选中的标题的字体大小
        float selectSize = unSelectSize * 1.07f; //选中后的标题的字体大小
        binding.moretabIndicator.setOnTransitionListener(new OnTransitionTextListener().setColor(0xFF333333, 0xFF949AA6).setSize(selectSize, unSelectSize));

        WindowManager winManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        screenPoint = new Point();
        winManager.getDefaultDisplay().getSize(screenPoint);
        drawableBar = new DrawableBar(this, getDrawable(R.drawable.silde_block));

        binding.moretabViewPager.setOffscreenPageLimit(versions.length - 1);
        indicatorViewPager = new IndicatorViewPager(binding.moretabIndicator, binding.moretabViewPager);
        myAdapter = new MyAdapter(getSupportFragmentManager());
        indicatorViewPager.setAdapter(myAdapter);
    }

    /**
     * 通过Activity中的public方法向Fragment传值
     */
    public RoadFacilitiesInvestigationTaskDTO.RoadFacilitiesTaskDTO pushFragmentData() {
        return roadFacilitiesTaskDTO;
    }

    private int getTextWidth(TextView textView) {
        if (textView == null) {
            return 0;
        }
        Rect bounds = new Rect();
        String text = textView.getText().toString();
        Paint paint = textView.getPaint();
        paint.getTextBounds(text, 0, text.length(), bounds);
        return bounds.left + bounds.width();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            List<String> photoSketchUploadIdArr = myAdapter.getPhotoSketchUploadIdArr();
            CustomPickerAdapterShowAndEdit photoSketchAdapter = myAdapter.getPhotoSketchAdapter();
            //拍照返回，或者视频录制返回
            if (isAdapterImagePickerResult(requestCode, photoSketchAdapter)) {
                ArrayList<MediaFile> mediaFileList = getMediaFileListWhenOnActivityResult(requestCode, data, photoSketchAdapter);
                saveFileAndRefreshAdapter(mediaFileList, photoSketchUploadIdArr, photoSketchAdapter,
                        FileUpload.RoadInvestigationFileBizTypeEnum.ROAD_FACILITIES_ALONG_FILE_BIZ_TYPE);
            }
        }
    }

    public class MyAdapter extends IndicatorViewPager.IndicatorFragmentPagerAdapter {

        public MyAdapter(FragmentManager fragmentManager) {
            super(fragmentManager);
        }

        @Override
        public int getCount() {
            return versions.length;
        }

        @Override
        public View getViewForTab(int position, View convertView, ViewGroup container) {
            if (convertView == null) {
                convertView = getLayoutInflater().inflate(R.layout.tab_top, container, false);
            }
            TextView textView = (TextView) convertView;
            textView.setText(versions[position]);
            //因为wrap的布局 字体大小变化会导致textView大小变化产生抖动，这里通过设置textView宽度就避免抖动现象
            //1.3f是根据上面字体大小变化的倍数1.3f设置
            textView.setWidth(screenPoint.x / 4);
            textView.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
            int textWidth = getTextWidth(textView);
            textWidths.add(textWidth);
            if (position == 0) {
                drawableBar.setWidth(textWidth);
                binding.moretabIndicator.setScrollBar(drawableBar);
            }
            return textView;
        }

        // 公交站点 Fragment
        private RoadFacilitiesBusStopFragment roadFacilitiesBusStopFragment;
        // 地铁站点 Fragment
        private RoadMetroStationFragment roadMetroStationFragment;
        // 地铁出入口 Fragment
        private RoadMetroStationGetwayFragment roadMetroStationGetwayFragment;
        // 路内停车 Fragment
        private RoadParkingFragment roadParkingFragment;
        // 自行车停放点 Fragment
        private RoadBicycleParkingFragment roadBicycleParkingFragment;
        // 过街设施 Fragment
        private RoadCrossingFacilitiesFragment roadCrossingFacilitiesFragment;
        // 收费站 Fragment
        private RoadTollGateFragment roadTollGateFragment;
        // 交通标志 Fragment
        private RoadTrafficSignFragment roadTrafficSignFragment;
        // 照片 Fragment
        private RoadSideFacilitiesFragment roadSideFacilitiesFragment;

        /**
         * 创建Fragment
         */
        @Override
        public Fragment getFragmentForPage(int position) {
            switch (position) {
                case 0:
                    // 公交站点
                    roadFacilitiesBusStopFragment = new RoadFacilitiesBusStopFragment();
                    return roadFacilitiesBusStopFragment;
                case 1:
                    // 地铁站点
                    roadMetroStationFragment = new RoadMetroStationFragment();
                    return roadMetroStationFragment;
                case 2:
                    // 地铁出入口
                    roadMetroStationGetwayFragment = new RoadMetroStationGetwayFragment();
                    return roadMetroStationGetwayFragment;
                case 3:
                    // 路内停车
                    roadParkingFragment = new RoadParkingFragment();
                    return roadParkingFragment;
                case 4:
                    // 自行车停放点
                    roadBicycleParkingFragment = new RoadBicycleParkingFragment();
                    return roadBicycleParkingFragment;
                case 5:
                    // 过街设施
                    roadCrossingFacilitiesFragment = new RoadCrossingFacilitiesFragment();
                    return roadCrossingFacilitiesFragment;
                case 6:
                    // 收费站
                    roadTollGateFragment = new RoadTollGateFragment();
                    return roadTollGateFragment;
                case 7:
                    // 交通标志
                    roadTrafficSignFragment = new RoadTrafficSignFragment();
                    return roadTrafficSignFragment;
                case 8:
                    // 照片
                    roadSideFacilitiesFragment = new RoadSideFacilitiesFragment();
                    return roadSideFacilitiesFragment;
            }
            return null;
        }

        public List<String> getPhotoSketchUploadIdArr() {
            return roadSideFacilitiesFragment.getPhotoSketchUploadIdArr();
        }

        public CustomPickerAdapterShowAndEdit getPhotoSketchAdapter() {
            return roadSideFacilitiesFragment.getPhotoSketchAdapter();
        }

        /**
         * 获取各个Fragment的数据
         */
        public void getFragmentsData() {
            roadFacilitiesTaskDTO.setRoadFacilitiesBusStop(roadFacilitiesBusStopFragment.getData());
            roadFacilitiesTaskDTO.setRoadMetroStation(roadMetroStationFragment.getData());
            roadFacilitiesTaskDTO.setRoadMetroStationGetway(roadMetroStationGetwayFragment.getData());
            roadFacilitiesTaskDTO.setRoadParking(roadParkingFragment.getData());
            roadFacilitiesTaskDTO.setRoadBicycleParking(roadBicycleParkingFragment.getData());
            roadFacilitiesTaskDTO.setRoadCrossingFacilities(roadCrossingFacilitiesFragment.getData());
            roadFacilitiesTaskDTO.setRoadTollGate(roadTollGateFragment.getData());
            roadFacilitiesTaskDTO.setRoadTrafficSign(roadTrafficSignFragment.getData());
            roadFacilitiesTaskDTO.setRoadFacilitiesAlongFileIds(roadSideFacilitiesFragment.getPhotoSketchUploadIdArr());
            roadFacilitiesTaskDTO.setRemoveRoadFacilitiesAlongFileIds(roadSideFacilitiesFragment.getDeletePhotoIdArr());
        }
    }
}